import { useState } from "react";
import { TreeSelect, Select } from "antd";

import { useComponentsStore, type Component, getComponentById } from "@editor/stores/components";
import { useComponentConfigStore } from "@editor/stores/component-config";

export interface ComponentMethodConfig {
    type: 'componentMethod',
    config: {
        componentId: number,
        method: string
    }
}

export interface ComponentMethodProps {
    value?: ComponentMethodConfig['config']
    onChange?: (config: ComponentMethodConfig) => void
}

export const ComponentMethod = (props: ComponentMethodProps) => {
    const { value, onChange } = props;
    const [curId, setCurId] = useState(value?.componentId)
    const [curMethod, setCurMethod] = useState(value?.method)

    const { components, curComponentId, } = useComponentsStore()
    const { componentConfig } = useComponentConfigStore()
    const [selectedComponent, setSelectComponent] = useState<Component | null>()

    const componentChange = (value: number) => {
        if (!curComponentId) return
        setCurId(value)
        setSelectComponent(getComponentById(value, components))
    }
    const ComponentMethodChange = (value: string) => {
        if (!curComponentId || !selectedComponent) return;

        setCurMethod(value)

        onChange?.({
            type: 'componentMethod',
            config: {
                componentId: selectedComponent?.id,
                method: value
            }
        })
    }

    return (
        <div className="mt-[40px]">
            <div className="flex items-center gap-[10px]">
                <div>组件：</div>
                <div>
                    <TreeSelect
                        style={{ width: 500, height: 50 }}
                        fieldNames={{
                            label: 'name',
                            value: 'id'
                        }}
                        value={curId}
                        onChange={(value) => { componentChange(value) }}
                        treeData={components}
                    />
                </div>
            </div>
            {
                componentConfig[selectedComponent?.name || ''] && (
                    <div className="flex items-center gap-[10px] mt-[20px]">
                        <div>方法：</div>
                        <div>
                            <Select style={{ width: 500, height: 50 }}
                                options={componentConfig[selectedComponent?.name || ''].methods?.map(method => ({ label: method.label, value: method.name }))}
                                value={curMethod}
                                onChange={(value) => { ComponentMethodChange(value) }} />
                        </div>
                    </div>
                )
            }
        </div>
    )
}